package czk.concrent.juc.cyclicbarrier.practice;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * CyclicBarrier可重复使用的线程栅格
 * 基于condition条件休息室实现
 *
 * @Author:ChenZhangKun
 * @Date: 2020/10/9 23:29
 */
public class CyclicBarrierDemo01 {
    public static void main(String[] args) throws InterruptedException {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(2, () -> {
            // 最后一个到达的线程来执行该任务
            System.out.println("最后一个线程到达了,线程名称是 " + Thread.currentThread().getName());
        });
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " 到达了");
            try {
                // 带超时的等待，超时后最后一个到达的线程不会执行到达后的任务
                cyclicBarrier.await(4, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        }).start();
        TimeUnit.SECONDS.sleep(3);
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " 到达了");
            try {
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
